package com.jck.ws.component.controller;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSON;
import com.jck.ws.component.model.BaseMessage;
import com.jck.ws.component.model.ChatMessage;
import com.jck.ws.component.model.User;
import com.jck.ws.component.service.UserService;

/**
 * 用户聊天功能
 */
@Controller
public class ChatController {

	private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm");
	// 用于转发数据(sendTo)
	@Autowired
	private SimpMessagingTemplate template;

	@Autowired
	private UserService userService;

	/**
	 * All.
	 *
	 * @param principal the principal
	 * @param message   the message
	 */
// 消息请求path
	@MessageMapping("/all")
	public void all(Principal principal, String message) {
		ChatMessage chatMessage = createMessage(principal.getName(), message);
		template.convertAndSend("/topic/notice", JSON.toJSONString(chatMessage));
	}

	/**
	 * Send to chat message.
	 *
	 * @param principal the principal
	 * @param message   the message
	 * @return the chat message
	 */
// 消息请求path
	@MessageMapping("/any-socket")
	@SendTo("/topic/notice2")
	public ChatMessage SendTo(Principal principal, String message) {
		ChatMessage chatMessage = createMessage(principal.getName(), message);
		return chatMessage;
	}

	/**
	 * Chat.
	 *
	 * @param principal the principal
	 * @param message   the message
	 */
// 消息请求path
	@MessageMapping("/chat")
	public void chat(Principal principal, String message) {
		BaseMessage baseMessage = JSON.parseObject(message, BaseMessage.class);
		baseMessage.setSender(principal.getName());
		this.send(baseMessage);
	}

	/*
	 * 异步处理 发送消息
	 */
	@Async
	private void send(BaseMessage message) {
		message.setDate(new Date());
		ChatMessage chatMessage = createMessage(message.getSender(), message.getContent());
		template.convertAndSendToUser(message.getReceiver(), "/topic/chat", JSON.toJSONString(chatMessage));
	}

	/**
	 *
	 * @param username
	 * @param message处理消息
	 * @return
	 */
	private ChatMessage createMessage(String username, String message) {
		ChatMessage chatMessage = new ChatMessage();
		chatMessage.setUsername(username);
		User user = userService.getByUsername(username);
		chatMessage.setAvatar(user.getAvatar());
		chatMessage.setNickname(user.getNickname());
		chatMessage.setContent(message);
		chatMessage.setSendTime(simpleDateFormat.format(new Date()));
		return chatMessage;
	}

}
